package com.sgb.kjwl.view.ui.fragment;

import android.Manifest;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.im.immodel.IMUtils;
import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentChatBinding;
import com.sgb.kjwl.view.ui.activity.MainActivity;
import com.sgb.kjwl.view.ui.activity.ScanActivity;
import com.sgb.kjwl.view.ui.activity.self.ApprovalManagerActvity;
import com.sgb.kjwl.view.ui.activity.self.SelfQrCodeActivity;
import com.sgb.kjwl.view.ui.activity.self.SuggestionFeedbackActivity;
import com.sgb.kjwl.view.ui.fragment.chat.ChatAddressBookFragment;
import com.sgb.kjwl.view.ui.fragment.chat.ChatNewsFragment;
import com.sgb.kjwl.view.widget.AddPopWindow;
import com.sgb.knowledgeshare.utils.SharePermissionUtils;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Author LiWei
 * Time 2021/11/9
 * Description: 新版消息界面IM版本1.1.0版本
 */
public class ChatFragment extends AppFragment {

    private FragmentChatBinding binding;
    private List<Fragment> mFragmentList;
    //当前正在显示的Fragment
    private Fragment mCurrentFragment;
    //更多IM相关功能Window
    private AddPopWindow addPopWindow;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_chat, container, false);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {
        binding.include.linTabAdd.setOnClickListener(this::onClick);
        binding.include.linTabNews.setOnClickListener(this::onClick);
        binding.include.linTabBook.setOnClickListener(this::onClick);
        binding.include.linTabUpcoming.setOnClickListener(this::onClick);
        binding.include.linTabShare.setOnClickListener(this::onClick);

        mFragmentList = new ArrayList<>();
        mFragmentList.add(ChatNewsFragment.newInstance());
        mFragmentList.add(ChatAddressBookFragment.newInstance());

        //默认选中初始位置
        changeFragment(0);
    }

    public void refreshChatFragment() {
        IMUtils.getInstance().refreshMessage();
        if (binding != null)
            changeFragment(0);
    }


    @Override
    public void onResume() {
        super.onResume();
        IMUtils.getInstance().refreshMessage();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lin_tab_news:   //消息
                changeFragment(0);
                break;
            case R.id.lin_tab_book:   //通讯录
                changeFragment(1);
                break;
            case R.id.lin_tab_upcoming://待办
                getPermission();
                break;
            case R.id.lin_tab_share:   //分享
                SharePermissionUtils.getPermission(getActivity());
                break;
            case R.id.lin_tab_add:
                if (addPopWindow != null) {
                    addPopWindow.showPopwindow(binding.include.ivAdd, true, 40);
                } else {
                    showAddPopWindow();
                }
                break;
        }
    }

    /**
     * 切换当前的选中的Fragment布局
     *
     * @param index 1:消息 2:通讯录
     */
    private void changeFragment(int index) {
        changeSelectStatus(index);
        FragmentTransaction fm = getChildFragmentManager().beginTransaction();
        if (null != mCurrentFragment) {
            fm.hide(mCurrentFragment);
        }
        Fragment fragment = mFragmentList.get(index);
        Fragment fragmentByTag = getChildFragmentManager().findFragmentByTag(fragment.getClass().getName());
        if (null == fragmentByTag) {
            fragmentByTag = fragment;
        }
        mCurrentFragment = fragmentByTag;
        if (!fragmentByTag.isAdded()) {
            fm.add(R.id.container, fragmentByTag, fragmentByTag.getClass().getName());
        } else {
            fm.show(fragmentByTag);
        }
        fm.commitAllowingStateLoss();
    }

    /**
     * 修改当前选中Tab的样式及指示器
     *
     * @param index 1:消息 2:通讯录
     */
    private void changeSelectStatus(int index) {
        binding.include.tvTabNews.setTextSize(15);
        binding.include.tvTabBook.setTextSize(15);
        binding.include.vTabNews.setVisibility(View.INVISIBLE);
        binding.include.vTabBook.setVisibility(View.INVISIBLE);
        switch (index) {
            case 0:
                binding.include.tvTabNews.setTextSize(16);
                binding.include.vTabNews.setVisibility(View.VISIBLE);
                break;
            case 1:
                binding.include.tvTabBook.setTextSize(16);
                binding.include.vTabBook.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    /**
     * 更多IM相关功能PopWindow
     */
    private void showAddPopWindow() {
        addPopWindow = new AddPopWindow(getActivity());
        addPopWindow.setOnClickCallBack(new AddPopWindow.OnClickCallBack() {
            @Override
            public void scan() { //扫一扫
                if (PermissionsUtil.hasPermission(getActivity(), Manifest.permission.CAMERA)) {
                    ScanActivity.start(getActivity());
                } else {
                    PermissionsUtil.requestPermission(getActivity(), new PermissionListener() {
                        @Override
                        public void permissionGranted(@NonNull String[] permissions) {
                            ScanActivity.start(getActivity());
                        }

                        @Override
                        public void permissionDenied(@NonNull String[] permissions) {
                            MToast.showLongToast(getActivity(), "请先获取相机权限");
                        }
                    }, Manifest.permission.CAMERA);
                }
            }

            @Override
            public void addFriend() { //添加好友
                IMUtils.getInstance().startFriend();
            }

            @Override
            public void groupChat() { //添加群聊
                IMUtils.getInstance().startGroupChat();
            }

            @Override
            public void qrCode() { //二维码
                SelfQrCodeActivity.start(getActivity());
            }

            @Override
            public void feedback() { //意见反馈
                SuggestionFeedbackActivity.start(getActivity());
            }
        });
        //初始化展开PopWindow
        addPopWindow.showPopwindow(binding.include.ivAdd, true, 40);
    }

    /**
     * 判断用户是否为企业身份 是:跳转待办界面 否:切换至用户中心
     */
    private void getPermission() {
        int TYPE = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
        String comNo = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NO, "");
        if (TYPE != 1 || TextUtils.isEmpty(comNo) || TextUtils.equals("0", comNo)) {
            showPermissionDialog();
        } else {
            ApprovalManagerActvity.start(getActivity(), 0);
        }
    }

    /**
     * 非企业用户中心提示弹框
     */
    public void showPermissionDialog() {
        String confirm = "确认";
        String content = "仅支持企业身份查看待办事项";
        View view = View.inflate(getActivity(), R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失

        TextView tv_confirm = (TextView) view.findViewById(R.id.tv_logout_confirm);
        TextView tv_message = (TextView) view.findViewById(R.id.tv_message);
        TextView tv_title = view.findViewById(R.id.tv_title);
        tv_title.setVisibility(View.VISIBLE);
        TextView tv_logout_cancel = (TextView) view.findViewById(R.id.tv_logout_cancel);
        tv_title.setText("温馨提示");
        tv_confirm.setText(confirm);
        tv_message.setText(content);
        //确定
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //切换界面至用户中心
                ((MainActivity) getActivity()).checkSelf();
                roundCornerDialog.dismiss();
            }
        });

        //取消
        tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }

}
